package com.chagee.channel.server.event.facade;

import cn.hutool.http.HttpUtil;
import com.chagee.base.constant.CommonErrorCode;
import com.chagee.base.utils.SoaResponse;
import com.chagee.base.utils.SoaUtil;
import com.chagee.channel.api.bo.lark.*;
import com.chagee.channel.api.service.ILarkServiceApi;
import com.chagee.channel.server.event.service.LarkService;
import com.chagee.channel.server.event.service.OssService;
import com.chagee.channel.server.util.HttpUtils;
import com.chagee.channel.server.util.ValidationResult;
import com.chagee.channel.server.util.ValidationUtils;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

/**
 * 飞书相关接口
 *
 * @author: chang.jiawei
 * @date: 2024/01/18
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LarkServiceRpcImpl implements ILarkServiceApi {

    private final LarkService larkService;
    private final OssService ossService;
    @Resource(name = "ttlExecutor")
    private ExecutorService threadPoolExecutor;

    @SneakyThrows
    @Override
    public SoaResponse<FileUploadResultBO, String> uploadFile(UploadFileBO uploadFile) {
        ValidationResult validationResult = ValidationUtils.validateEntity(uploadFile);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.FAIL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        return SoaUtil.ok(larkService.upload2Lark(uploadFile));
    }

    @Override
    public SoaResponse<FileUploadResultBO, String> uploadFileWithUrl(UploadFileUrlBO uploadFile) {
        ValidationResult validationResult = ValidationUtils.validateEntity(uploadFile);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.FAIL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }

        String finalUrl = uploadFile.getUrl().replaceAll("\u0026", "&");
        byte[] pic = HttpUtils.downloadBytes(finalUrl);
        UploadFileBO param = UploadFileBO.transfer(uploadFile, pic);
        return SoaUtil.ok(larkService.upload2Lark(param));
    }

    @SneakyThrows
    @Override
    public SoaResponse<FileUploadWithOssResultBO, String> uploadLarkAndOssWithUrl(UploadFileUrlBO uploadFile) {
        String finalUrl = uploadFile.getUrl().replaceAll("\u0026", "&");
        byte[] pic = HttpUtils.downloadBytes(finalUrl);
        UploadFileBO param = UploadFileBO.transfer(uploadFile, pic);
        Future<FileUploadResultBO> larkFuture = threadPoolExecutor.submit(() -> larkService.upload2Lark(param));
        Future<String> ossFuture = threadPoolExecutor.submit(() -> ossService.upload(pic, uploadFile.getFileName()));
        return SoaUtil.ok(new FileUploadWithOssResultBO(larkFuture.get(60, TimeUnit.SECONDS), ossFuture.get(60, TimeUnit.SECONDS)));
    }

    @Override
    public SoaResponse<String, Void> startApprove(StartApprovalBO startApprovalBO) {
        ValidationResult validationResult = ValidationUtils.validateEntity(startApprovalBO);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.FAIL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        return SoaUtil.ok(larkService.startApprove(startApprovalBO));
    }

    @Override
    public SoaResponse<Void, Void> approveApprove(ApproveApprovalBO approveApprovalBO) {
        ValidationResult validationResult = ValidationUtils.validateEntity(approveApprovalBO);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.FAIL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        larkService.approveApprove(approveApprovalBO);
        return SoaUtil.ok(null);
    }

    @Override
    public SoaResponse<Void, Void> revokeApprove(RevokeApprovalBO revokeApprovalBO) {
        ValidationResult validationResult = ValidationUtils.validateEntity(revokeApprovalBO);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.FAIL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        larkService.revokeApprove(revokeApprovalBO);
        return SoaUtil.ok(null);
    }

    @Override
    public SoaResponse<ApprovalInstanceDetailBO, Void> approvalInstanceDetail(String instanceCode) {
        ValidationResult validationResult = ValidationUtils.validateEntity(instanceCode);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.PARAMETER_IS_NULL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        return SoaUtil.ok(larkService.approvalInstanceDetail(instanceCode));
    }


    @Override
    public SoaResponse<List<ApprovalPreviewNodeBO>, Void> approvalInstancePreview(PreviewApprovalBO previewApprovalBO) {
        ValidationResult validationResult = ValidationUtils.validateEntity(previewApprovalBO);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.PARAMETER_IS_NULL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        return SoaUtil.ok(larkService.approvalInstancePreview(previewApprovalBO));
    }

    @Override
    public SoaResponse<ApprovalDetailBO, Void> approvalDetail(String approvalCode) {
        ValidationResult validationResult = ValidationUtils.validateEntity(approvalCode);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.PARAMETER_IS_NULL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        return SoaUtil.ok(larkService.approvalDetail(approvalCode));
    }

    @Override
    public SoaResponse<ApprovalCommentListResponse, Void> approvalCommentsList(ApprovalCommentListRequest request) {
        ValidationResult validationResult = ValidationUtils.validateEntity(request);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.PARAMETER_IS_NULL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        return SoaUtil.ok(larkService.approvalCommentsList(request));
    }


    @Override
    public SoaResponse<ApprovalCarbonCopyResponse, Void> approvalCarbonCopy(ApprovalCarbonCopyRequest request) {
        ValidationResult validationResult = ValidationUtils.validateEntity(request);
        if (validationResult.isHasErrors()) {
            return SoaUtil.error(CommonErrorCode.PARAMETER_IS_NULL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
        }
        return SoaUtil.ok(larkService.approvalCarbonCopy(request));
    }
	/**
	 * 审批实例详情-全文评论
	 *
	 * @param instanceCode
	 * @return
	 */
	@Override
	public SoaResponse<ApprovalCommentsBO, Void> approvalInstanceComment(String instanceCode) {
		ValidationResult validationResult = ValidationUtils.validateEntity(instanceCode);
		if (validationResult.isHasErrors()) {
			return SoaUtil.error(CommonErrorCode.PARAMETER_IS_NULL.getErrorCode(), validationResult.getErrorMsg().toString(), null);
		}
		ApprovalInstanceDetailBO approvalInstanceDetailBO = larkService.approvalInstanceDetail(instanceCode);

		if (CollectionUtils.isNotEmpty(approvalInstanceDetailBO.getCommentList())) {
			return SoaUtil.ok(larkService.approvalInstanceComment(instanceCode, approvalInstanceDetailBO.getCommentList().get(0).getUserId()));
		}
		return SoaUtil.ok(null);
	}

}
